<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
  <!--引入vue的包-->
  <script src="../../js/vue.js"></script>
  <!--引入axios的包-->
  <script src="../../js/axios.min.js"></script>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../css/index.css">
  <!--引入组件库-->
  <script src="../../js/index.js"></script>
</head>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }
</style>
<body>
<div id="app">
    <!--表头上面的搜索刷新等-->
    <el-row :gutter="20">
        <el-col :span="5">
            <el-input v-model="searchForm.userName" placeholder="请输入用户名" size="small"></el-input>
        </el-col>
        <el-col :span="5">
            <el-input v-model="searchForm.phonenumber" placeholder="请输入手机号码" size="small"></el-input>
        </el-col>
        <el-col :span="3"></el-col>
        <el-col :span="3">
            <el-button type="success" size="medium" icon="el-icon-search" @click="search">搜索</el-button>
        </el-col>
        <el-col :span="3">
            <el-button type="primary" size="medium" icon="el-icon-circle-plus-outline" @click="handleAdd">添加</el-button>
        </el-col>
        <el-col :span="3">
            <el-button type="warning" size="medium" icon="el-icon-refresh" @click="refresh">刷新</el-button>
        </el-col>
        <el-col :span="2"></el-col>
    </el-row>
        <!--前端显示的页面-->
        <el-table
                :data="tableData"
                style="width: 100%">
            <el-table-column
                    prop="userId"
                    label="用户Id"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="loginName"
                    label="登录账号"
                    width="120">
            </el-table-column>
            <el-table-column
                    prop="avatar"
                    label="头像"
                    width="120">
                <template slot-scope="scope">
                    <el-image :src="scope.row.avatar" style="width: 100px; height: 100px"></el-image>
                </template>
            </el-table-column>
            <el-table-column
                    prop="userName"
                    label="用户昵称"
                    width="120">
            </el-table-column>
            <el-table-column
                    prop="email"
                    label="用户邮箱"
                    width="140">
            </el-table-column>
            <el-table-column
                    prop="phonenumber"
                    label="手机号码"
                    width="140">
            </el-table-column>
            <el-table-column
                    prop="sex"
                    label="用户性别"
                    :formatter="getsex"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="password"
                    label="密码"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="salt"
                    label="盐值"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="帐号状态"
                    :formatter="getstatus"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="delFlag"
                    label="删除标志"
                    :formatter="getdel"
                    width="100">
            </el-table-column>
            <el-table-column
                    prop="loginIp"
                    label="最后登陆IP"
                    width="140">
            </el-table-column>
            <el-table-column
                    prop="loginDate"
                    label="最后登陆时间"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="createBy"
                    label="创建者"
                    width="120">
            </el-table-column>
            <el-table-column
                    prop="updateTime"
                    label="修改时间"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    label="创建时间"
                    width="160">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="300">
                <template slot-scope="scope">
                    <el-button
                            size="mini" type="success" @click="handleRole(scope.$index, scope.row)">授予角色
                    </el-button>
                    <el-button
                            size="small"
                            class="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                            size="small"
                            type="danger"
                            class="el-icon-delete"
                            @click="handleDelete(scope.$index, scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    <!--进行分页操作-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!--授予角色表单-->
    <el-dialog
            title="角色列表"
            :visible.sync="dialogVisible"
            width="30%">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
        </el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
            <el-checkbox v-for="role in roleList" :label="role.roleId" :key="role.roleId">{{role.roleName}}
            </el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUserAndRole">确 定</el-button>
        </span>
    </el-dialog>

    <!--进行添加操作-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules">
            <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="loginName">
                <el-input v-model="form.loginName" autocomplete="off" placeholder="请输入用户昵称"></el-input>
            </el-form-item>
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
                <el-input v-model="form.userName" autocomplete="off"  placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="头像" :label-width="formLabelWidth" prop="avatar">
                <el-upload
                        class="avatar-uploader"
                        action="/user/avatar"
                        :show-file-list="false"
                        accept=".jpg,.png"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
                <el-input v-model="form.email" autocomplete="off"  placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" :label-width="formLabelWidth" prop="phonenumber">
                <el-input v-model="form.phonenumber" autocomplete="off"  placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" :label-width="formLabelWidth" prop="sex">
                <el-select v-model="form.sex" placeholder="请选择性别">
                    <el-option label="男" value="0"></el-option>
                    <el-option label="女" value="1"></el-option>
                    <el-option label="未知" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                <el-input v-model="form.password" autocomplete="off"  placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="账号状态" :label-width="formLabelWidth" prop="status">
                <el-select v-model="form.status" placeholder="请选择帐号状态">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="停用" value="1"></el-option>
                </el-select>
            </el-form-item>
           <!-- <el-form-item label="" :label-width="formLabelWidth" prop="addTime">
                <el-date-picker
                        v-model="form.addTime"
                        type="datetime"
                        value-format="yyyy-MM-dd hh:mm:ss"
                        placeholder="请设置订单时间">
                </el-date-picker>
            </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrupdate">确 定</el-button>
        </div>
    </el-dialog>

    <!--进行修改操作-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible1">
        <el-form :model="form" :rules="rules">
            <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="loginName">
                <el-input v-model="form.loginName" autocomplete="off" placeholder="请输入用户昵称"></el-input>
            </el-form-item>
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
                <el-input v-model="form.userName" autocomplete="off"  placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="头像" :label-width="formLabelWidth" prop="avatar">
                <el-upload
                        class="avatar-uploader"
                        action="/user/avatar"
                        :show-file-list="false"
                        accept=".jpg,.png"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
                <el-input v-model="form.email" autocomplete="off"  placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" :label-width="formLabelWidth" prop="phonenumber">
                <el-input v-model="form.phonenumber" autocomplete="off"  placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" :label-width="formLabelWidth" prop="sex">
                <el-select v-model="form.sex" placeholder="请选择性别">
                    <el-option label="男" value="0"></el-option>
                    <el-option label="女" value="1"></el-option>
                    <el-option label="未知" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="账号状态" :label-width="formLabelWidth" prop="status">
                <el-select v-model="form.status" placeholder="请选择帐号状态">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="停用" value="1"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible1 = false">取 消</el-button>
            <el-button type="primary" @click="addOrupdate1">确 定</el-button>
        </div>
    </el-dialog>
</div>
</body>
<script>
  new Vue({
    el:"#app",
    data(){
      return{
          //表单验证
          rules: {
              loginName: [
                  {required: true, message: '长度在 2 到 10 个字符', trigger: 'blur'},
                  {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
              ],
              userName: [
                  {required: true, message: '长度在 2 到 10 个字符', trigger: 'blur'},
                  {min: 3, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
              ],
              password: [
                  {required: true, message: '请输入密码', trigger: 'blur'},
                  {min: 6, max: 10, message: '由6-10字母和数字组成', trigger: 'blur'},
                  {
                      required: true,
                      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/,
                      message: '必须由6-10字母和数字组成',
                      trigger: 'blur'
                  }
              ],
          },
          tableData:[],//把表单设置一个空的集合
          currentPage:1,//设置当前页是第几页
          pageSize:3,//设置一页有几行数据
          searchForm:{userName:"",phonenumber:""},//进行模糊查询设置的参数
          total: 100,//设置总条数
          title: "用户添加",
          dialogFormVisible:false,//设置表框默认情况下是不显示的
          dialogFormVisible1:false,//设置修改的操作表
          form:{
              "loginName":"","userName":"","avatar":"","email":"",
              "phonenumber":"","sex":"","password":"","status":""
          },
          formLabelWidth: '120px',
          imageUrl:'', //上传照片设置
          //添加新用户的角色
          dialogVisible:false, //默认情况下不弹出
          checkAll: false, //是否全选
          checkedRoles: [], //默认选中的角色
          roleList:[], //   有效角色集合
          roleIds: "",//定义所有选中角色id集合
          isIndeterminate: true,
          tempUserId: 0, //用户id
          value: '',
      }
    },
    created(){
        //用户一开始就加载，分页
      this.loadDate();
      //获取所有的角色
      this.getHaveRole();
    },
    methods:{
        loadDate(){
            var _this=this;
            axios.post('/user/queryByPage', {
                "pageNo":this.currentPage,"pageSize":this.pageSize,"data":{
                 "userName":this.searchForm.userName,"phonenumber":this.searchForm.phonenumber
                }
            }).then(function (response) {
                //进行判断，如果return的code值是对的，，执行下一步
               // alert(JSON.stringify(response))
                if(response.data.code==200){
                    //获取全部的数据
                    _this.total=response.data.data.total;
                    //获取所有的数据
                    _this.tableData=response.data.data.list;
                }else {
                    //先不处理错误
                }
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        //处理添加
        handleAdd(){
            //进行title的设置
            this.title="用户添加";
            //当点击的时候，让弹框显示
            this.dialogFormVisible=true;
            //添加的时候，让form表单为空
            this.form={};
        },
        //处理修改
        handleEdit(index,row){
            //因为添加要是让数据回显，因此不能为空
            this.form=row;
            this.title="用户修改";
            //当点击的时候，让弹框显示
            this.dialogFormVisible1=true;
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.loadDate();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val;
            this.loadDate();
        },
        search(){
            this.loadDate();
        },
        //刷新方法
        refresh() {
            //location.reload() 方法用来刷新当前页面
            location.reload();
        },
        //添加操作
        addOrupdate(){
            //定义变量
            var _this=this;
            axios.get("/user/checkuserName?userName="+this.form.userName).then(function (response){
                    if(response.data == true){
                        axios.post("/user/add",  //请求的url
                            _this.form) //请求的参数，json格式
                            .then(function (response) { //回调函数
                                //前端控制台打印，response是json对象
                                //console.log(JSON.stringify(response));
                                //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
                                if (response.data.code == 200) {
                                    //alert(JSON.stringify(response));
                                    //提示成功
                                    _this.$message({
                                        message: '执行成功',
                                        type: 'success'
                                    });
                                    //关闭弹框
                                    _this.dialogFormVisible = false;
                                    //重新加载数据
                                    _this.loadData();
                                } else {
                                    _this.$message.error('执行失败');
                                }
                            })
                            .catch(function (error) {//异常处理
                                console.log(error);
                            });
            }else {
                        _this.$message.error('用户名已存在');
                    }
            })
        },
        //修改操作
        addOrupdate1(){
            var _this=this;
            axios.post("/user/update",_this.form).then(function (response){
                //进行判断，code是200的话，正常执行
                if(response.data.code==200){
                    _this.$message({
                        message:"执行成功",
                        type:"success",
                    })
                    //执行成功之后，关闭弹框
                    _this.dialogFormVisible1=false;
                    //再次加载页面
                    _this.loadDate();
                }else {
                    _this.$message.error("执行失败")
                }
            }).catch(function (error){
                console.log(error)
            });
        },

        //进行删除处理
        handleDelete(index,row){
            console.log(row)
            //定义一个变量
            var _this=this;
            this.$confirm('确定要删除该数据?', '提示', {
                type: 'warning'
            }).then(() => {
            axios.delete("/user/deleteById?userId="+row.userId).then(function (response){
                if(row.userId ==1){
                    _this.$message.error('超级管理员不能被删除');
                }else {
                    //进行判断，如果成功，就继续执行
                    if(response.data.code==200){
                        _this.$message({
                            message:"删除成功",
                            type:"success",
                        })
                        //删除成功之后，直接重新加载页面
                        _this.loadDate();
                    }else {
                        _this.$message.error("删除失败")
                    }
                }
            }).catch((error) => {//异常处理
                console.log("删除失败的原因:",error)
            })
        }).catch(() => {
      this.$message({
          type: 'info',
          message: '已取消删除'
      });
            })
        },

        //获取用户性别，把数字转为字符
        getsex(row) {
            switch (row.sex) {
                case '0':
                    return '男'
                case '1':
                    return '女'
                case '2':
                    return '未知'
            }
        },
        //获取用户的状态
        getstatus(row) {
            switch (row.status) {
                case '0':
                    return '正常'
                case '1':
                    return '停用'
            }
        },
        //获取用户的删除标志
        getdel(row) {
            switch (row.delFlag) {
                case '0':
                    return '存在'
                case '1':
                    return '删除'
            }
        },
        //刷新方法
        refresh() {
            //location.reload() 方法用来刷新当前页面
            location.reload();
        },
        //获取所有角色
        getHaveRole() {
            var _this = this;
            // 使用axios向后台发请求
            axios.post("/role/queryByPage",
                {"pageNo": 1, "pageSize": 100})
                .then(function (response) { //回调函数
                    console.log(response);//前端控制台打印
                    //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
                    if (response.data.code == 200) {
                        _this.roleList = response.data.data.list;
                    } else {
                        _this.$message.error('执行失败');
                    }
                })
                .catch(function (error) {//异常处理
                    console.log(error);
                });
        },
        //获取当前用户已经拥有的角色
        handleRole(index, row) {
            //定义变量
            tempUserId = row.userId;
            this.dialogVisible = true; //让对话框显示
            //定义变量
            tempUserId = row.userId;
            var _this = this;
            // 使用axios向后台发请求
            axios.get("/userRole/queryByUserId?userId=" + row.userId).then(function (response) { //回调函数
                console.log(response);//前端控制台打印，response是json对象
                console.log(JSON.stringify(response));
                if (response.data.code == 200) {
                    _this.checkedRoles = [];
                    for (var i = 0; i < response.data.data.length; i++) {
                        //把查询到的角色添加到集合里
                        _this.checkedRoles.push(response.data.data[i].roleId);
                        console.log(JSON.stringify(_this.checkedRoles));
                    }
                } else {
                    _this.$message.error('执行失败');
                }
            })
                .catch(function (error) {//异常处理
                    console.log(error);
                });
        },
        //给用户添加角色
        addUserAndRole() {
            var _this = this;
            var roleIdsArrray = this.roleIds.toString().split(",");
            for (var i = 0; i < roleIdsArrray.length; i++) {
                // 使用axios向后台发请求
                axios.post("/userRole/add",
                    {"userId": tempUserId, "roleId": roleIdsArrray[i]}
                ) //请求的参数，json格式
                    .then(function (response) { //回调函数
                        //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
                        if (response.data.code == 200) {
                            //提示成功
                            _this.$message({
                                message: '执行成功',
                                type: 'success',
                            });
                            //关闭弹框
                            _this.dialogVisible = false;
                        } else {
                            _this.$message({
                                message: '请至少添加一个角色',
                                type: 'success',
                            });
                        }
                    })
                    .catch(function (error) {//异常处理
                        console.log(error);
                    });
            }

        },
        //角色全选
        handleCheckAllChange(val) {
            if (val) {
                this.checkedRoles = []
                for (let i = 0; i < this.roleList.length; i++) {
                    this.checkedRoles.push(this.roleList[i].roleId);
                }
                this.roleIds = this.checkedRoles;//把勾选的角色id赋值给roleIds
            } else {
                this.checkedRoles = []
            }
            this.isIndeterminate = false;
        },
        //勾选角色
        handleCheckedRolesChange(value) {
            this.roleIds = value; //把勾选的角色id赋值给roleIds
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.roleList.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
        },
        //选择文件
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            console.log(file) //file里面的data就是图片的链接
            this.form.avatar = file.response.data;//将图片链接的数据赋给表单的avatar属性
        },
        //上传前处理逻辑
        beforeAvatarUpload(file) {
            console.log("图片")
            console.log(file)
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt5M = file.size / 1024 / 1024 < 5;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
            }
            if (!isLt5M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return (isJPG || isPNG) && isLt5M;
        },
    }
  })
</script>
</html>